package com.zhang.service.impl;

import com.zhang.dao.OrderItemMapper;
import com.zhang.dao.OrderMapper;
import com.zhang.entity.Order;
import com.zhang.entity.OrderItem;
import com.zhang.service.OrderService;
import com.zhang.utils.MyBatisUtils;
import org.apache.ibatis.session.SqlSession;

import java.util.ArrayList;
import java.util.List;

public class OrderServiceImpl implements OrderService {
    @Override
    public void insert(Order order) {
        SqlSession sqlSession = null;
        try {
            sqlSession = MyBatisUtils.getSqlSession();
            OrderMapper dao = sqlSession.getMapper(OrderMapper.class);
            OrderItemMapper dao2 = sqlSession.getMapper(OrderItemMapper.class);

            dao.insert(order);

            List<OrderItem> orderItemList = order.getOrderItemList();
            for (OrderItem orderItem:orderItemList) {
                orderItem.setOrder_id(order.getId());
                dao2.insert(orderItem);
            }
            sqlSession.commit();
        } catch (Exception e) {
            sqlSession.rollback();
            throw new RuntimeException(e);
        } finally {
            MyBatisUtils.closeSqlSession(sqlSession);
        }
    }

    @Override
    public List<Order> selectAll(int uid) {
        List<Order> orderList = new ArrayList<>();
        SqlSession sqlSession = null;
        try {
            sqlSession = MyBatisUtils.getSqlSession();
            OrderMapper dao = sqlSession.getMapper(OrderMapper.class);
            orderList = dao.selectAll(uid);
            sqlSession.commit();
        } catch (Exception e) {
            sqlSession.rollback();
            throw new RuntimeException(e);
        } finally {
            MyBatisUtils.closeSqlSession(sqlSession);
        }
        return orderList;
    }

    @Override
    public void changeState(int id) {
        SqlSession sqlSession = null;
        try {
            sqlSession = MyBatisUtils.getSqlSession();
            OrderMapper dao = sqlSession.getMapper(OrderMapper.class);
            dao.changeState(id);
            sqlSession.commit();
        } catch (Exception e) {
            sqlSession.rollback();
            throw new RuntimeException(e);
        } finally {
            MyBatisUtils.closeSqlSession(sqlSession);
        }
    }
}
